package com.carlinfo.shop.head.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.carlinfo.shop.common.util.ConstatFinalUtil;
import com.carlinfo.shop.common.util.PageInfoUtil;
import com.carlinfo.shop.common.web.controller.BaseController;
import com.carlinfo.shop.goods.pojo.AGoods;
import com.carlinfo.shop.goods.pojo.AGoodsCate;
import com.carlinfo.shop.goods.pojo.AGoodsEnum;
import com.carlinfo.shop.goods.pojo.AUsersCar;
import com.carlinfo.shop.goods.service.IGoodsService;
import com.carlinfo.shop.users.pojo.AUsers;

/**
 * 所有前台Controller,不需要登陆就可以访问
 * @author wangshMac
 *
 */
@Controller
public class IndexHeadController extends BaseController
{
	@Resource
	private IGoodsService goodsService;
	
	/**
	 * 首页
	 * @return
	 */
	@RequestMapping("/main")
	public String main()
	{
		ConstatFinalUtil.LOGGER.info("====main====");
		return "/head/main";
	}
	
	/**
	 * 网页的头部
	 * 由于网页头部的中的数据是活的,要查询数据库
	 * 只能使用动态包含
	 * @return
	 */
	@RequestMapping("/header")
	public String header(Model model,HttpServletRequest request,HttpServletResponse response)
	{
		ConstatFinalUtil.LOGGER.info("====header====");
		/* 查询所有的分类,要树形结构 */
		/* 查询树形结构的分类 */
		List<AGoodsCate> cateList = this.goodsService.findTreeListGoodsCateService();
		model.addAttribute("cateList", cateList);
		
		/* 为了取购物车的数量,在网页的头部显示 */
		this.carList(request, response);
		
		return "/head/header";
	}
	
	/**
	 * 商品列表页面
	 * @return
	 */
	@RequestMapping("/goods")
	public String goods(Model model)
	{
		ConstatFinalUtil.LOGGER.info("====goods====");
		Map<String, Object> requMap = new HashMap<String, Object>();
		return goodsList(requMap,model);
	}
	
	/**
	 * 商品分页
	 * SpringMVC驱动,可以直接从url取值
	 * @pathVariable一定要和{}中间的值一样;也得和url中键=值&键=值中的键一样
	 * http://localhost:10001/shop-web-head/goods_23232.html
	 * 
	 * 分类id
	 * 关键字放到url?后面的内容;不从url路径中获取
	 * @return
	 */
	@RequestMapping("/goods_{cateId}_{currentPage}")
	public String goods(@PathVariable String cateId , @PathVariable String currentPage ,String keyword,
			HttpServletRequest request , 
			Model model)
	{
		ConstatFinalUtil.LOGGER.info("====goods====");
		Map<String, Object> requMap = new HashMap<String, Object>();
		if(cateId == null)
		{
			cateId = ""; 
		}
		if("".equalsIgnoreCase(cateId))
		{
			/* 从请求头的键=值&键=值中键再尝试获取一次 */
			cateId = request.getParameter("cateId");
		}
		
		/* 当前页 */
		requMap.put("currentPage", currentPage);
		requMap.put("cateId", cateId);
		requMap.put("keyword", keyword);
		return goodsList(requMap,model);
	}

	/**
	 * 查询商品列表的工具类
	 * @param model
	 * @return
	 */
	private String goodsList(Map<String, Object> requMap , Model model)
	{
		/* 查询商品的数据 */
		/* 一定得分页 */
		String currentPage = requMap.get("currentPage") + "";
		PageInfoUtil pageInfoUtil = this.proccedPageInfoUtil(currentPage, ConstatFinalUtil.SYS_CONFIG_JSON.get("pageInfo.head.size") + "");
		
		String keyword = (String) requMap.get("keyword");
		String cateId = (String) requMap.get("cateId");
		
		if(keyword == null)
		{
			keyword = ""; 
		}
		keyword = keyword.trim() ; 
		if(cateId == null)
		{
			cateId = "" ; 
		}
		
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 添加将来的搜索条件 */
		/* 搜索启用的数据 */
		condMap.put("status", AGoodsEnum.STATUS_ENABLE.getStatus());
		condMap.put("keyword", keyword);
		if(!"".equalsIgnoreCase(cateId))
		{
			condMap.put("cateId", cateId);
		}
		Map<String, Object> resultMap = this.goodsService.findCondListGoodsService(pageInfoUtil, condMap);
		/* 商品列表 */
		List<AGoods> goodsList = (List<AGoods>) resultMap.get("list");
		int totalRecord = Integer.valueOf(resultMap.get("totalRecord") + "");
		/* 分页有效,得设置总条数 */
		pageInfoUtil.setTotalRecord(totalRecord);
		
		/* 设置到四大作用域中 */
		model.addAttribute("goodsList", goodsList);
		model.addAttribute("pageInfoUtil", pageInfoUtil);
		/* 存储搜索条件 */
		model.addAttribute("keyword", keyword);
		model.addAttribute("cateId", cateId);
		return "/head/goods";
	}
	
	/**
	 * 商品详情页面
	 * @return
	 */
	@RequestMapping("/goods/{url}")
	public String goodsInfo(@PathVariable String url, Model model)
	{
		ConstatFinalUtil.LOGGER.info("====goods====");
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("url", url);
		AGoods goods = this.goodsService.findOneGoodsService(condMap);
		/* request.setAttribute("goods",goods); */
		model.addAttribute("goods", goods);
		return "/head/goodsInfo";
	}
	
	/**
	 * 添加购物车
	 * 返回值是json;说了就是告诉购物车是否添加成功
	 * 
{
	"code":"0",
	"info":""
}
	 * @return
	 */
	@RequestMapping(value = "/carInsert",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String carInsert(HttpServletRequest request,HttpServletResponse response)
	{
		ConstatFinalUtil.LOGGER.info("==carInsert==");
		JSONObject resultJSON = new JSONObject() ; 
		resultJSON.put("code", "1");
		resultJSON.put("info", ConstatFinalUtil.INFO_JSON.getString("1"));
		
		String goodsId = request.getParameter("goodsId");
		String num = request.getParameter("num");
		
		if(goodsId == null)
		{
			goodsId = "" ; 
		}
		if(num == null)
		{
			num = "" ; 
		}
		
		if("".equalsIgnoreCase(goodsId))
		{
			/* 木有传商品的id */
			resultJSON.put("code", "2");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.getString("2"));
		}
		if("".equalsIgnoreCase(num))
		{
			/* 木有传数量 */
			resultJSON.put("code", "3");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.getString("3"));
		}
		
		/* 不管是登陆还是木有登陆,request中存储的集合名字一定得一样;
		 * usersCarList
		 *  */
		/* 判断一下用户是否登陆 */
		HttpSession session = request.getSession() ; 
		AUsers users = (AUsers) session.getAttribute("users");
		Map<String, Object> condMap = new HashMap<String, Object>();
		if(users != null)
		{
			/* 登陆后 */
			/* 向数据库中保存一条购物车的信息就可以 */
			condMap.clear();
			condMap.put("usersId", users.getId());
			condMap.put("goodsId", Integer.valueOf(goodsId));
			AUsersCar usersCar = this.goodsService.findOneUsersCarService(condMap);
			boolean updateFlag = true ; 
			/* 
			 * 如果存在,创建对象,赋值(只需要更新num),就更新,
			 * 如果不存在,赋值,就添加(更新用户id,和goodsid)
			 * */
			if(usersCar == null)
			{
				usersCar = new AUsersCar() ; 
				/* 更新用户id,和goodsid */
				usersCar.setUsersId(users.getId());
				usersCar.setGoodsId(Integer.valueOf(goodsId));
				
				usersCar.setCreateTime(new Date());
				/* 假设错误 */
				updateFlag = false ; 
			}
			
			usersCar.setStatus(Byte.valueOf("1"));
			/* usersCar:肯定不为空 */
			usersCar.setNum(usersCar.getNum() + Integer.valueOf(num));
			
			usersCar.setUpdateTime(new Date());
			usersCar.setPubTime(new Date());
			
			/* 如何才能知道,是更新数据库呢?还是添加数据呢? */
			if(updateFlag)
			{
				this.goodsService.updateOneUsersCarService(usersCar);
			}else
			{
				this.goodsService.saveOneUsersCarService(usersCar);
			}
		}else
		{
			/* 登陆前 */
			/* 从Cookie中获取购物车数据 */
			JSONArray shopCarArr = this.findShopCarFromCookie(request);
			
			/* 一开始,假设此商品在购物车里面木有
			 * true:此商品在购物车中木有
			 * false:此商品在购物车中有
			 *  */
			boolean carFlag = true ; 
			/* 先判断一下,此商品在购物车里面有木有 */
			for (Iterator iterator = shopCarArr.iterator(); iterator.hasNext();)
			{
				JSONObject goodsJSON = (JSONObject) iterator.next();
				if(goodsId.equalsIgnoreCase(goodsJSON.getString("id")))
				{
					/* 说明购物车里面有此商品 */
					goodsJSON.put("num", Integer.valueOf(num) + Integer.valueOf(goodsJSON.get("num") + ""));
					carFlag = false ; 
				}
			}
			
			if(carFlag)
			{
				/* 准备一个商品和数量,放数组中放
				 * 要想知道此商品是不是在购物车里面有,
				 * 得先走一遍循环
				 *  */
				JSONObject shopJSON = new JSONObject() ; 
				shopJSON.put("id", goodsId);
				shopJSON.put("num", num);
				/* 万一此商品在购物车里面有,用户又点击了一次;要在原来的数量上+指定的数量 */
				shopCarArr.add(shopJSON);
			}
			
			this.saveShopCarFormCookie(shopCarArr, request, response);
		}
		
		
		
		resultJSON.put("code", "0");
		resultJSON.put("info", ConstatFinalUtil.INFO_JSON.getString("0"));
		
		return resultJSON.toJSONString();
	}
	
	/**
	 * 购物车列表页面
	 * @return
	 */
	@RequestMapping("/carList")
	public String carList(HttpServletRequest request,HttpServletResponse response)
	{
		ConstatFinalUtil.LOGGER.info("==carList==");
		/* 不管是登陆还是木有登陆,request中存储的集合名字一定得一样;
		 * usersCarList
		 *  */
		/* 判断一下用户是否登陆 */
		HttpSession session = request.getSession() ; 
		AUsers users = (AUsers) session.getAttribute("users");
		if(users != null)
		{
			/* 登陆了 */
			/* 要按照用户id查询所有的购物车 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			/* 按照用户id */
			condMap.clear();
			condMap.put("usersId", users.getId());
			Map<String, Object> resultMap = this.goodsService.findCondListUsersCarService(null, condMap);
			List<AUsersCar> usersCarList = (List<AUsersCar>) resultMap.get("list");
			
			/* 存储四大作用域 */
			request.setAttribute("usersCarList", usersCarList);
		}else
		{
			/* 木有登陆 */
			/* 从Cookie中获取购物车数据 */
			JSONArray shopCarArr = this.findShopCarFromCookie(request);
			
			/* 购物车列表 */
			List<AUsersCar> usersCarList = new ArrayList<AUsersCar>();
			Map<String, Object> condMap = new HashMap<String, Object>();
			/* 购物车里面放的是商品的id和商品的数量,
			 * 最终期望往request里面放一个List<AUsersCar> */
			for (Iterator iterator = shopCarArr.iterator(); iterator.hasNext();)
			{
				JSONObject carTemp = (JSONObject) iterator.next();
				String id = carTemp.get("id") + "" ;
				String num = carTemp.get("num") + "" ; 
				
				/* auserscar */
				AUsersCar usersCar = new AUsersCar() ; 
				usersCar.setGoodsId(Integer.valueOf(id));
				usersCar.setNum(Integer.valueOf(num));
				/* 放一个商品的关联对象 */
				/* 根据id查询商品 */
				condMap.clear();
				condMap.put("id", id);
				AGoods goods = this.goodsService.findOneGoodsService(condMap);
				usersCar.setGoods(goods);
				
				/* 将购物车放到List中 */
				usersCarList.add(usersCar);
			}
			
			/* 存储四大作用域 */
			request.setAttribute("usersCarList", usersCarList);
		}
		return "/head/carlList" ; 
	}
	
	/**
	 * 购物车删除
	 * @return
	 */
	@RequestMapping("/carDelete")
	public String carDelete(String[] goodsIds,HttpServletRequest request,HttpServletResponse response)
	{
		ConstatFinalUtil.LOGGER.info("==carDelete==");
		HttpSession session = request.getSession() ; 
		AUsers users = (AUsers) session.getAttribute("users");
		Map<String, Object> condMap = new HashMap<String, Object>();
		if(goodsIds != null)
		{
			JSONArray shopCarArr = this.findShopCarFromCookie(request);
			for (int i = 0; i < goodsIds.length; i++)
			{
				String goodsId = goodsIds[i];
				/* 未登陆,操作Cookie,
				 * 登陆操作数据库
				 *  */
				if(users != null)
				{
					/* 操作数据库 */
					condMap.clear();
					condMap.put("usersId", users.getId());
					condMap.put("goodsId", goodsId);
					AUsersCar usersCar = this.goodsService.findOneUsersCarService(condMap);
					this.goodsService.deleteOneUsersCarService(usersCar);
				}else
				{
					JSONObject removeJSON = null ; 
					/* 操作Cookie */
					for (Iterator iterator = shopCarArr.iterator(); iterator.hasNext();)
					{
						JSONObject tempJSON = (JSONObject) iterator.next();
						if(goodsId.equalsIgnoreCase(tempJSON.getString("id")))
						{
							removeJSON = tempJSON ; 
							break ; 
						}
					}
					
					if(removeJSON != null)
					{
						shopCarArr.remove(removeJSON);
					}
					
					/* 保存数据 */
					this.saveShopCarFormCookie(shopCarArr, request, response);
				}
			}
		}
		
		/* 返回购物车列表页面 */
		/*return this.carList(request, response) ; */
		/* 不想灌水,使用客户端跳转 */
		return "redirect:/carList.html" ;
	}
}
